<?php
declare (strict_types = 1);

namespace app\api\controller\finance;

use app\admin\model\user\User;
use app\admin\model\user\UserBank;
use app\api\controller\Base;
use app\validate\WithdrawValidate;
use think\exception\ValidateException;
use app\common\service\finance\Withdraw as cash;

class Withdraw extends Base
{

    /**
     * Author:Yingbo Sun
     * 提现申请接口
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function requestWithdraw()
    {
        $post = $this->request->post();
        $uid = $this->request->uid;
        try {
            validate(WithdrawValidate::class)->check([
                'bank_id'  => $post['bank_id'],
                'cash_price' => $post['cash_price'],
            ]);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            $data = ['code' => 400, 'message' => $e->getError()];
            return $this->res($data);
        }
        //正则判断价钱是否有无
        if (!preg_match('/^(([1-9]\d*)|0)(\.\d{1-2})?$/', $post['cash_price'])) {
            $data = ['code' => 400,'message' => '提现金额有无'];
            return $this->res($data);
        }
//        $uid = 18;
        //判断余额
        $user = User::where('id',$uid)->find();
        if ($user->fake_money < $post['cash_price']){
            $data = ['code' => 400,'message' => '账户余额不足，提现失败'];
            return $this->res($data);
        }
        $bank = UserBank::where('id',$post['bank_id'])->find();
        //正则判断银行卡是否有无
        if (!preg_match('/^([1-9]{1})(\d{14}|\d{18})$/',$bank->credit_card_numbers)){
            $data = ['code' => 400,'message' => '银行卡号有误'];
            return $this->res($data);
        }
        $code = verifyCode();
        $post['withdraw_time'] = time();
        $post['cash_no'] = 'EA' . time() . $code;
        $post['uid'] = $uid;
        //提现申请
        $res = cash::cash($post);
        return $this->res($res);
    }
}
